import { isThisYear } from 'date-fns';
import imSDK from 'openim-uniapp-polyfill';
import dayjs from 'dayjs';
import { MessageType } from '@openim/client-sdk';
import type { MessageItem } from '@openim/client-sdk';
import useUserStore from '@/store/user';
import calendar from 'dayjs/plugin/calendar';
import relativeTime from 'dayjs/plugin/relativeTime';
import updateLocale from 'dayjs/plugin/updateLocale';

export const IMSDK = imSDK;
export const IMMethods = imSDK.IMMethods;
export const IMEvents = imSDK.IMEvents;

dayjs.extend(calendar);
dayjs.extend(relativeTime);
dayjs.extend(updateLocale);

const linkWrap = ({ userID, name, groupID }: { userID: string; name: string; groupID: string }) => {
  return `<span class='link-el truncate inline-block align-bottom' onclick='userClick("${userID}","${
    groupID ?? ''
  }")'>${name}</span>`;
};

export const tipMessaggeFormat = (msg: MessageItem) => {
  const userStore = useUserStore();
  const selfID = userStore.selfInfo.userID;

  switch (msg.contentType) {
    case MessageType.FriendAdded:
      return '你们已经是好友了，开始聊天吧';
    case MessageType.RevokeMessage: {
      const data = JSON.parse(msg.notificationElem?.detail || '{}');
      const operator = data.revokerID === selfID ? '你' : data.revokerNickname;
      const revoker = data.sourceMessageSendID === selfID ? '你' : data.sourceMessageSenderNickname;
      const isAdminRevoke = data.revokerID !== data.sourceMessageSendID;

      if (isAdminRevoke) {
        const operatorStr = linkWrap({
          userID: data.revokerID,
          groupID: msg.groupID,
          name: operator,
        });
        const revokerStr = linkWrap({
          userID: data.sourceMessageSendID,
          groupID: msg.groupID,
          name: revoker,
        });

        return `${operatorStr}撤回了一条${revokerStr}发送的消息`;
      }

      const revokerStr = linkWrap({
        userID: data.revokerID,
        groupID: msg.groupID,
        name: operator,
      });

      return `${revokerStr}撤回了一条消息`;
    }
    case MessageType.OANotification: {
      const customNoti = JSON.parse(msg.notificationElem?.detail || '{}');
      return customNoti.text;
    }
    default:
      return '';
  }
};

export const getCleanText = (text: string) => {
  return text.replace(/<\/?([a-z][a-z0-9]*)\b[^>]*>/gi, '');
};

export const formatMessageTime = (timestemp: number, keepSameYear = false): string => {
  if (!timestemp) return '';

  const isRecent = dayjs().diff(timestemp, 'day') < 7;
  const keepYear = keepSameYear || !isThisYear(timestemp);

  if (!isRecent && !keepYear) {
    return dayjs(timestemp).format('M/D HH:mm');
  }

  return dayjs(timestemp).calendar();
};

const regex =
  /\b(https?:\/\/|www\.)[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(:\d+)?(\.[a-zA-Z]{2,})?(\/[a-zA-Z0-9/._-]*(\?\S*)?(#\S*)?)?\b/g;

export const formatLink = (content: string) =>
  content.replace(regex, match => {
    let href = match;
    if (!match.match(/^https?:\/\//)) {
      href = 'https://' + match;
    }
    return `<a href="${href}" target="_blank" class="link-el">${match}</a>`;
  });

export const parseBr = (text: string) => {
  return text.replace(new RegExp('\\n', 'g'), '<br>').replace(new RegExp('\\n', 'g'), '<br>');
};

export const formatConversionTime = (timestemp: number): string => {
  if (!timestemp) return '';

  const fromNowStr = dayjs(timestemp).fromNow();

  if (fromNowStr.includes('秒')) {
    return '刚刚';
  }

  if (!fromNowStr.includes('秒') && !fromNowStr.includes('分钟')) {
    return dayjs(timestemp).calendar();
  }

  return fromNowStr;
};

export const formatMessageByType = (message: MessageItem): string => {
  const userStore = useUserStore();
  const isSelf = (id: string) => id === userStore.storeSelfInfo.userID;

  switch (message.contentType) {
    case MessageType.TextMessage:
      return message.textElem?.content || '';
    case MessageType.AtTextMessage: {
      let mstr = message.atTextElem?.text || '';
      const pattern = /@\S+\s/g;
      const arr = mstr.match(pattern);
      arr?.map(a => {
        const member = (message.atTextElem?.atUsersInfo ?? []).find(
          gm => gm.atUserID === a.slice(1, -1)
        );
        if (member) {
          const reg = new RegExp(a, 'g');
          mstr = mstr.replace(reg, `@${member.groupNickname} `);
        }
      });
      return mstr;
    }
    case MessageType.PictureMessage:
      return '[图片]';
    case MessageType.VideoMessage:
      return '[视频]';
    case MessageType.VoiceMessage:
      return '[语音]';
    case MessageType.LocationMessage: {
      const locationInfo = JSON.parse(message.locationElem?.description || '{}');
      return `[位置]${locationInfo.name}`;
    }
    case MessageType.FileMessage:
      return `[文件]${message.fileElem?.fileName}`;
    case MessageType.RevokeMessage: {
      const data = JSON.parse(message.notificationElem?.detail || '{}');
      const revokerID = data.revokerID;
      const revoker = isSelf(revokerID) ? '你' : data.revokerNickname;
      const isAdminRevoke = data.revokerID !== data.sourceMessageSendID;

      if (isAdminRevoke) {
        return `${data.sourceMessageSendNickname}撤回了一条${revoker}发送的消息`;
      }
      return `${revoker}撤回了一条消息`;
    }
    default:
      return '';
  }
};

export const getConversationContent = (message: MessageItem) => {
  const userStore = useUserStore();
  if (
    !message.groupID ||
    message.sendID === userStore.storeSelfInfo.userID ||
    message.contentType === MessageType.GroupAnnouncementUpdated
  ) {
    return formatMessageByType(message);
  }
  return `${message.senderNickname}：${formatMessageByType(message)}`;
};
